 /**
 * @Description: 商品分类
 * @author  tangbin
 * @date 2023/3/10
 */

<template>
  <div class="app-containers">
    <query-table-render
        ref="queryTable"
        :query-model="queryModel"
        :table-request="requestTableData"
        :table-column="tableColumns"
        :title-render="titleRender"
        :toolbar-render="toolbarRnd"
        :transform-query="transformQuery"
        @on-operator="onOperator"
    >
      <template v-slot:form>
        <el-form-item label="商品类别" prop="category">
          <el-select v-model="queryModel.category" placeholder="请选择" style="width:100%" clearable>
            <el-option
                v-for="item in dict.type.basic_data_goods_type"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="queryModel.name" placeholder="请输入" clearable @keyup.enter.native="searchListQuery"/>
        </el-form-item>
        <el-form-item label="分类编号" prop="code">
          <el-input v-model="queryModel.code" placeholder="请输入" clearable @keyup.enter.native="searchListQuery"/>
        </el-form-item>
        <el-form-item label="开票主体" prop="drawer">
          <el-select v-model="queryModel.drawer" placeholder="请选择" style="width:100%" clearable>
            <el-option
                v-for="item in dict.type.basic_data_company"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="收款主体" prop="payee">
          <el-select v-model="queryModel.payee" placeholder="请选择" style="width:100%" clearable>
            <el-option
                v-for="item in dict.type.basic_data_company"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
          </el-select>
        </el-form-item>
      </template>
    </query-table-render>

    <!-- 新增修改页面 -->
    <el-dialog :title="title" :visible.sync="open" width="505px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="104px">
        <el-form-item label="分类编号:" prop="code" v-show="!isAdd">
          <el-input v-model="form.code" placeholder="请输入" size="small" maxlength="200" disabled />
        </el-form-item>
        <el-form-item label="分类名称:" prop="name">
          <el-input v-model.trim="form.name" placeholder="请输入" size="small" maxlength="200" clearable />
        </el-form-item>
        <el-form-item label="商品类别:" prop="category">
          <el-select
            size="small"
            v-model="form.category"
            placeholder="请选择"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="dict in dict.type.basic_data_goods_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="收款主体:" prop="payee">
          <el-select
            size="small"
            v-model="form.payee"
            placeholder="请选择"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="dict in dict.type.basic_data_company"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开票主体:" prop="drawer">
          <el-select
            size="small"
            v-model="form.drawer"
            placeholder="请选择"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="dict in dict.type.basic_data_company"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称拼接:" prop="joinName" label-width="104px">
          <el-checkbox v-model="form.joinName"></el-checkbox>
        </el-form-item>
        <el-form-item label="备注:">
          <el-input v-model.trim="form.remark" :autosize="{ minRows: 5, maxRows: 10}" type="textarea" maxlength="500" show-word-limit placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="saveloading">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
// import auth from '@/plugins/auth'
import {checkPermi} from '@/utils/permission.js'
import QueryTableRender from "@/components/QueryTableRender";
import {goodsClassList, goodsClassSave, goodsClassUpdate} from '@/api/basic/goodsClass.js'
import dayjs from "dayjs";
export default {
  name: 'CommodityClassify',
  dicts: ['basic_data_goods_type', 'basic_data_company'], // 商品类别，业务主体(开票主体，收款主体)
  components: {QueryTableRender},
  data() {
    return {
      // disabled: false,
      saveloading: false,
      title: '', // 弹窗标题
      open: false, // 是否显示弹窗
      isAdd: true, // 是否新增
      // goodsCategoryOptions: [{label: '甲类', value: 1}, {label: '乙类', value: 2}], // 商品类别
      // tmpOptions: [{label: '天津', value: 1}, {label: '周平', value: 2}, {label: '济南', value: 3}],
      joinNameOptions: [{label: '是', value: true}, {label: '否', value: false}], // 是否拼接
      queryModel: {}, // 查询参数
      tableColumns: [], // 表头字段
      form: {},
      rules: {}
    }
  },
  created() {
    this.setupRules();
    this.setupQueryModel();
    this.setupTableColumns();
  },
  
  methods: {
    setupRules() {
      this.rules = {
        name: [
          {required: true, message: "分类名称不能为空", trigger: "blur"}
        ],
        payee: [
        {required: true, message: "请选择收款主体", trigger: "change"}
        ],
        drawer: [
        {required: true, message: "请选择开票主体", trigger: "change"}
        ]
      };
    },
    /**
     * 初始化查询条件参数
     */
     setupQueryModel() {
      const params = {
        category: undefined, // 商品类别
        name: undefined, // 分类名称
        code: undefined, // 分类编号
        drawer: undefined, // 开票主体
        payee: undefined, // 收款主体
      };
      this.queryModel = {
        ...this.queryModel,
        ...params
      };
    },
    
    setupTableColumns() {
      this.tableColumns = [
        {
          label: '序号',
          width: '60',
          type: 'index',
          increment: true
        },
        {
          prop: 'code',
          label: '分类编号',
          minWidth: '200',
        },
        {
          prop: 'name',
          label: '分类名称',
          minWidth: '160',
          showOverflowTooltip: true
        },
        {
          prop: 'category',
          label: '商品类别',
          minWidth: '120',
          render: (h, text) => {
            let show = "";
            this.dict.type.basic_data_goods_type.some((item) => {
              if (item.value === text) {
                show = item.label;
                return true;
              }
            });
            return show;
          }
        },
        {
          prop: 'payee',
          label: '收款主体',
          minWidth: '160',
          showOverflowTooltip: true,
          render: (h, text) => {
            let show = "";
            this.dict.type.basic_data_company.some((item) => {
              if (item.value === text) {
                show = item.label;
                return true;
              }
            });
            return show;
          }
        },
        {
          prop: 'payBank',
          label: '收款账户',
          minWidth: '160',
          showOverflowTooltip: true
        },
        {
          prop: 'payAccount',
          label: '收款账号',
          minWidth: '180',
          showOverflowTooltip: true
        },
        {
          prop: 'drawer',
          label: '开票主体',
          minWidth: '160',
          render: (h, text) => {
            let show = "";
            this.dict.type.basic_data_company.some((item) => {
              if (item.value === text) {
                show = item.label;
                return true;
              }
            });
            return show;
          }
        },
        {
          prop: 'joinName',
          label: '商品名称拼接',
          minWidth: '120',
          render: (h, text) => {
            let show = text;
            this.joinNameOptions.some((item) => {
              if (item.value === text) {
                show = item.label;
                return true;
              }
            });
            return show;
          }
        },
        {
          prop: 'remark',
          label: '备注',
          minWidth: '260',
          showOverflowTooltip: true
        },
        {
          label: '操作',
          width: '100',
          type: 'operator',
          align: "left",
          fixed: 'right',
          operators: this.operatorsFunc()
          // operators: [{label: '修改', command: 'edit', permissions: 'basicdata:commodity:edit'}]
        },
        
      ];
    },

    /**
     * 标题渲染
     * @param {*} h 
     */
    titleRender(h) {
      return <div>
        <span style="display:inline-block; background-color: #1890FF;margin-bottom: -2px; margin-right: 8px; width: 3px; height: 14px"></span>
        <span style="display: inline-block; color: #333333; font-size: 16px;">商品分类</span>
      </div>;
    },

    /**
     * 渲染功能列表
     * @param {*} h 
     */
    toolbarRnd(h) {
      let list = [];
      if (checkPermi(['basic-data:goods-class:save'])) {
        list.push(<el-button type="primary" icon="el-icon-plus" size="small" vOn:click={() => this.addCategory()}>新增分类</el-button>);
      }
      return list;
    },

    /**
     * 搜索列表查询
     */
     searchListQuery() {
      this.$refs['queryTable'].submitQuery();
    },

    /**
     * 操作列表
     */
    operatorsFunc() {
      let list = [];
      if (checkPermi(['basic-data:goods-class:update'])) {
        list.push({label: '修改', command: 'edit'});
      }
      return list;
    },

    /**
     * 请求数据获取数据
     * @param {*} queryParams 
     */
    requestTableData(queryParams) {
      // console.log('queryParams=', queryParams);
      return goodsClassList(queryParams).then(respData => {
          // console.log('rspData=', respData);
          return {
            success: true,
            total: respData.data.total,
            data: respData.data.records,
          }
        }
      ).catch(err => {
      });
    },

    /**
     * 修改参数格式
     * @param {*} queryData 
     */
    transformQuery(queryData) {
      // console.log('queryData=', queryData);
      let transParams = {};
      for (let keyName in queryData) {
        if (queryData.hasOwnProperty(keyName)) {
          if (keyName === 'createTimeRange') {
            // if(queryData['createTimeRange'] && queryData['createTimeRange'].length){
            //   const [start, end] =  queryData[keyName]
            //   transParams['startTime'] = dayjs(start).startOf('day').format("YYYY-MM-DD HH:mm:ss")
            //   transParams['endTime'] = dayjs(end).endOf('day').format("YYYY-MM-DD HH:mm:ss")
            // }
          } else {
            transParams[keyName] = queryData[keyName]
          }
        }
      }
      return transParams;
    },

    /**
     * 刷新列表
     */
    onRefreshTable(){
      this.$refs['queryTable'].refreshTable();
    },

    /**
     * 重置
     */
    resetForms() {
      this.form = {
        code: undefined, // 分类编号
        name: undefined, // 分类名称
        category: undefined, // 商品类别
        payee: undefined, // 收款主体
        drawer: undefined, // 开票主体
        joinName: false, // 是否拼接
        remark: undefined, // 备注
      };
      // this.$refs['form'].resetFields();
      this.resetForm("form");
    },

    /**
     * 新增分类
     */
    addCategory() {
      this.resetForms();
      this.title = '新增商品分类';
      this.open = true;
      this.isAdd = true;
    },

    /**
     * 修改数据
     * @param {*} record 
     */
    updateCategory(record) {
      this.resetForms();
      this.form = JSON.parse(JSON.stringify(record));
      this.title = '修改商品分类';
      this.open = true;
      this.isAdd = false;
    },

    /**
     * 操作页面
     * @param {*} command 
     * @param {*} record 
     */
    onOperator(command, record) {
      if('edit' === command){
        this.updateCategory(record)
      }
    },

    /**
     * 取消
     */
     cancel() {
      this.resetForms();
      this.disabled = false;
      this.open = false;
    },

    /**
     * 新增或者修改
     */
     submitForm() {
      this.$refs['form'].validate(valid => {
        if (!valid) {
          this.saveloading = false;
          return;
        }
        if (this.form.id != undefined) {
          // 修改
          goodsClassUpdate(this.form).then(res => {
            // console.log('res=', res);
            if (res) {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.onRefreshTable();
              }
              this.saveloading = false;
          }).catch(err => {
            this.saveloading = false;
          });
        } else {
          // 新增
          goodsClassSave(this.form).then(res => {
            // console.log('熙增=', res);
            if (res) {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.onRefreshTable();
            }
            this.saveloading = false;
          }).catch(err => {
            this.saveloading = false;
          });
        }
      });
     },

  },
}
</script>

<style lang="scss" scoped>
</style>